<?php

/**
 * Task
 *-------------------------
 *
 * Deal with menu display, selected status. Top menu - sub menu
 *
 * PHP versions 5
 *
 * LICENSE: This source file is from Smarter Ver4.0, which is a comprehensive shopping engine
 * that helps consumers to make smarter buying decisions online. We empower consumers to compare
 * the attributes of over one million products in the computer and consumer electronics categories
 * and to read user product reviews in order to make informed purchase decisions. Consumers can then
 * research the latest promotional and pricing information on products listed at a wide selection of
 * online merchants, and read user reviews on those merchants.
 * The copyrights is reserved by http://www.mezimedia.com.
 * Copyright (c) 2005, Mezimedia. All rights reserved.
 *
 * @author     james.huang <james_huang@mezimedia.com>
 * @copyright  (C) 2004-2008 Mezimedia.com
 * @license    http://www.mezimedia.com  PHP License 5.2
 * @version    CVS: $Id: UserController.php
 * @link       http://pms.mezimedia.com/
 * @deprecated File deprecated in Release 1.0
 */

include_once 'TaskConfigure.php';

class Task extends TaskConfigure {
	public $_db = null;
	public $_config = null;
	public $_filter_list = array ();
	public $_sorter_list = array ();
	public $_raw_task_list = array ();
	public $_sup_task_list = array ();
	public $_entities = array ();

	public function __construct() {
		$this->_db = Zend_Registry :: get('db_adapter');
		$this->_name = 'tt_st_task';
		$this->_primary = 'id';
		parent::_setup();
		// get configure entities
		$this->_config = new TaskConfigure();
		$this->_entities = $this->_config->_init();
	}

	public function setFilter($filter_list = array ()) {
		$this->_filter_list = $filter_list;
	}

	/**
	 * fetch filter sql for task list
	 *
	 * @param string $prefix	# add 'and' or 'or' condition for sql
	 * @return string			# return filter sql, return '' if filter is empty
	 * @throws
	 */
	public function getFilter($prefix = '') {
		if (sizeof($this->_filter_list) <= 0) return '';
		$filter_arr = array ();
		foreach ($this->_filter_list as $k => $v) {
			if (strlen($v) <= 0 || (is_numeric($v) && $v <= 0))
				continue;
			if ($k == 'title') {
				array_push($filter_arr, '(' . $k . ' like \'%' . $v . '%\' or id=\''.$v.'\')');
			} else {
				array_push($filter_arr, $k . ' = ' . $v);
			}
		}
//		Utils::dumper($filter_arr);
		if (sizeof($filter_arr) > 0) {
			return $prefix . implode(' and ', $filter_arr);
		} else {
			return '';
		}
	}

	public function setSorter($sorter_list = array ()) {
		$this->_sorter_list = $sorter_list;
	}
	
	public function setSequence($sTaskId, $tTaskId) {		
		$tTask = $this->find($tTaskId)->toArray();
		if (!empty($tTask)) {
			$tSeq = $tTask[0]['sequence'];
			$sql = "update tt_st_task set sequence=sequence+1 where sequence>=$tSeq and id!='$tTaskId'";
			$this->_db->query($sql);				
			$sql = "update tt_st_task set sequence=$tSeq+1 where id='$sTaskId'";
			$this->_db->query($sql);
		}
	}

	/**
	 * fetch filter sql for task list
	 *
	 * @return array			# return array, return array() if sorter is empty
	 * @throws
	 */
	public function getSorter() {
		if (sizeof($this->_sorter_list) <= 0) return array();
		$sorter_arr = array ();
		foreach ($this->_sorter_list as $k => $v) {
			array_push($sorter_arr, $k . ' ' . $v);
		}
//		Utils::dumper($sorter_arr);
		return $sorter_arr;
	}

	public function getEntities($type = null) {
		if ($type) {
			return $this->_entities[$type];
		}
		return $this->_entities;
	}

	public function getEntityValue($type = null, $key = null) {
		if ($type) {
			$entity = $this->_entities[$type];
			if ($key) {
				//if (!isset($entity[$key])) echo $type;
				return $entity[$key];
			}
		}
		return '--';
	}

	/**
	 * specific task update
	 *
	 * @param array $data
	 * @param integer $id
	 * @return
	 * @throws Zend_Db_Exception
	 */
	public function update(array $data, $id) {
		$where = $this->_db->quoteInto('id = ?', $id);
		parent :: update($data, $where);
	}

	public function updateWeight($data = array ()) {
		try {
			//Utils::dumper($data);
			foreach ($data as $k => $v) {
				$where = $this->_db->quoteInto('id = ?', $k);
				parent :: update(array (
					'weight' => $v
				), $where);
			}
		} catch (Zend_Db_Table_Exception $e) {
			echo $e->getMessage();
		}
	}

	public function getCols() {
		return $this->_cols;
	}

	/**
	 * specific task update
	 *
	 * @param boolean $finished
	 *
	 * @return string
	 * @throws Zend_Db_Exception
	 */
	public function getWhereSQL($finished = false) {
		$filter = $this->getFilter(' and ');		
		if (!$filter) {
			// get all super tasks which sup_task_id equal 0
			$where = $this->_db->quoteInto('sup_task_id = ?', 0);
		} else {
			// get tasks by filter as a result of super tasks
			$where = $this->_db->quoteInto('sup_task_id != ?', -1);
		}
		if ($finished) {
			if (strpos($where, 'task_status') === false) {
				$where .= ' and task_status in('.__TASK_FINISHED.')';
			}
			//$where .= ' and task_status = '.__TASK_FINISHED.' and progress = 100 ';
		} else {
			if (strpos($where, 'task_status') === false) {
				$where .= ' and task_status not in (2,9)';
			}
			//$where .= ' and (task_status != '.__TASK_FINISHED.' || progress != 100) ';
		}
		//$where .= ' and task_status != '.__TASK_CANCELED.' '; // does not display cancel tasks
		$where .= $filter;

		return $where;
	}

	/**
	 * get sort sql for getting tasks
	 *
	 * @param boolean $finished
	 *
	 * @return string
	 * @throws Zend_Db_Exception
	 */
	public function getSortSQL($finished = false) {
		$order = array (
			'task_prior desc',
			'task_status desc'
		);
		if ($finished) {
			$order_sql = "launch_date='0000-00-00',launch_date desc";
		} else {
			$sorter = $this->getSorter();
			if (sizeof($sorter) > 0) {
				$order = array_merge($sorter, $order);
			}
			array_unshift($order, "date_end='0000-00-00'"); // sort default date to the end of the list
			array_unshift($order, 'sequence desc');
			$order_sql = implode(",",$order);
		}
		
		return $order_sql;
	}

	/**
	 * get total task count
	 *
	 * @param boolean $finished
	 *
	 * @return numberic
	 * @throws Zend_Db_Exception
	 */
	public function getTotal($finished = false) {
		try {
			$sql = 'select count(id) from ' . $this->_name . ' where '.$this->getWhereSQL($finished);			
			if (isset($_REQUEST['debug']) && $_REQUEST['debug'] == 'sql') echo '[SQL:getTotal] '.$sql.'<br/>';
			$sum = $this->_db->fetchOne($sql);
		}
		catch (Zend_Db_Table_Exception $e) {
			echo $e->getMessage();
		}
		return $sum;
	}

	/**
	 * get sub task list according to given super tasks
	 *
	 * @param array $sup_task_ids
	 *
	 * @return null
	 * @throws Zend_Db_Exception
	 */
	public function getRawTaskList($sup_task_ids = array (0)) {
		try {
			$where = $this->_db->quoteInto('sup_task_id IN (?)', $sup_task_ids);
			$sup_tasks = $this->fetchAll($where, 'sup_task_id asc, id');
			if (count($sup_tasks)) {
				$sup_sub_task_ids = array ();
				foreach ($sup_tasks as $sup_task) {
					$task_id = $sup_task->__get('id');
					if (in_array($task_id, $sup_task_ids)) continue;
					array_push($this->_raw_task_list, $sup_task->toArray());
					array_push($sup_sub_task_ids, $task_id);
				}
				// call self to rebuild again
				if (sizeof($sup_sub_task_ids) > 0) {
					$this->getRawTaskList($sup_sub_task_ids);
				}
			}
		} catch (Zend_Db_Table_Exception $e) {
			echo $e->getMessage();
		}
	}

	/**
	 * get super task list
	 *
	 * @param int $count
	 * @param int $offset
	 * @param boolean $finished
	 *
	 * @return array()
	 * @throws Zend_Db_Exception
	 */
	public function getSuperTaskIds($count = 1, $offset = 0, $finished = false)
	{
		$sup_task_ids = array(-1); // should not be empty for preventing sql error
		$top_tasks = array();

		try {
			// build sql
			$where = $this->getWhereSQL($finished);
			$order = $this->getSortSQL($finished);
			// get top tasks by condition
			$sql = "select * from {$this->_name} where {$where} order by {$order} limit {$offset}, {$count}";
			if (isset($_REQUEST['debug']) && $_REQUEST['debug'] == 'sql') echo '[SQL:getSuperTaskIds] '.$sql.'<br/>';
			$sup_tasks = $this->_db->fetchAll($sql);
			if (count($sup_tasks) > 0) {
				foreach ($sup_tasks as $sup_task) {
					if (0 == $sup_task['sup_task_id']) {
						array_push($sup_task_ids, $sup_task['id']);
						array_push($this->_raw_task_list, $sup_task);
					} else {
						array_push($top_tasks, $sup_task);
					}
				}
			}

			// add super tasks for condition pages
			foreach ($top_tasks as $top_task) {
				if (!in_array($top_task['sup_task_id'], $sup_task_ids)) {
					$top_task['sup_task_id'] = 0; // force to be super task
					array_push($this->_raw_task_list, $top_task);
					array_push($sup_task_ids, $top_task['id']);
				}
			}

		} catch (Zend_Db_Table_Exception $e) {
			echo $e->getMessage();
		}

//		Utils::dumper($this->_raw_task_list);
//		Utils::dumper($sup_task_ids);

		return $sup_task_ids;
	}

	/*get the new task count for a user*/
	public function getTaskCounts($userId) {
		$sql = "select count(*) as num, task_status from " . $this->_name . " where (developer_id =" . $userId . " OR manager_id=" . $userId . " OR request_id=" . $userId . ") group by task_status";
		$taskCounts = $this->_db->fetchAll($sql);
		$taskCountArr = array ();
		foreach ($taskCounts as $taskCount) {
			$taskCountArr['ts_' . $taskCount['task_status']] = $taskCount['num'];
		}
		return $taskCountArr;
	}

	public function getTaskPrior($referId) {
//		Utils::dumper($this->_entities);
		if (isset($this->_entities['prior_reference'][$referId])) {
			$reference = $this->_entities['prior_reference'][$referId];
			$prior_name = trim(substr($reference, 0, strpos($reference,':')));
			return array_search($prior_name, $this->_entities['prior']);
		}
		return false;
	}

	/*
	 * Get task list by given filter parameters
	 * $params: date_start, date_end, request_id, manager_id, developer_id, task_status
	 * */
	public function getFilteredTasks($params = array ()) {
		$taskList = array ();
		$sql = 'select id, date_start, date_end, request_id, manager_id, developer_id, task_status, title, progress , prior_reference from tt_st_task where  sup_task_id<1';
		$sqltail = "";

		if (count($params) > 0) {
			$sqltail .= " and tt_st_task.date_end>='".$params['startDate']."'";
			$sqltail .= " and tt_st_task.date_start<='".$params['endDate']."'";
		}

		$sql .= $sqltail . " and task_status != -1 order by id desc";
		
		$taskList = $this->_db->fetchAll($sql);

		$userLists=$this->getUserLists();

		$prior_reference=$this->getEntities();
		$prior_reference=$prior_reference['prior_reference'];

		for($i=0;$i<count($taskList);$i++){

			$taskList[$i]['Requester']=$this->getUserNameFromUserLists($taskList[$i]['request_id'],$userLists);
			$taskList[$i]['PM']=$this->getUserNameFromUserLists($taskList[$i]['manager_id'],$userLists);
			$taskList[$i]['Resource']=$this->getUserNameFromUserLists($taskList[$i]['developer_id'],$userLists);
			$taskList[$i]['Prior']=$this->getPrior($taskList[$i]['prior_reference'],$prior_reference);
		}
		return $taskList;
	}

	/*
	 * Get task list by given filter parameters
	 * $params: date_start, date_end, request_id, manager_id, developer_id, task_status
	 * */
	public function getFilteredTasksByRpt($params = array ()) {
		$taskList = array ();
		$sql = 'select id, date_start, date_end, request_id, duration, property_id, manager_id, developer_id, task_status, title, progress , prior_reference from tt_st_task where  sup_task_id<1';
		$sqltail = "";

		if (isset($params['startDate'])) {
			$sqltail .= " and ("
					 .  "	 (tt_st_task.date_start>='".$params['startDate']."' and tt_st_task.date_start<='".$params['endDate']."')"
					 .  " or (tt_st_task.date_end>='".$params['startDate']."' and tt_st_task.date_end<='".$params['endDate']."')"
					 .  " or (tt_st_task.date_start<'".$params['startDate']."' and tt_st_task.date_end>'".$params['endDate']."')"
					 .  " )";
		}
		if (isset($params['engineers'])) {
			$sqltail .= " and developer_id in (".$params['engineers'].")";
		}
		if (isset($params['statuss'])) {
			$sqltail .= " and task_status in (".$params['statuss'].")";
		}
		if (isset($params['notinstatus'])) {
			$sqltail .= " and task_status not in (".$params['notinstatus'].")";
		}
		if (isset($params['propertys'])) {
			$sqltail .= " and property_id in (".$params['propertys'].")";
		}

		$sql .= $sqltail . " and task_status != -1";
		if (isset($params['orderby'])) {
			$sql .= " order by ".$params['orderby']."";
		}

		if($params['debug']=="yes"){
			echo $sql;
		}
		$taskList = $this->_db->fetchAll($sql);

		$userLists=$this->getUserLists();

		$prior_reference=$this->getEntities();
		$prior_reference=$prior_reference['prior_reference'];
		for($i=0;$i<count($taskList);$i++){
			$taskList[$i]['Requester']=$this->getUserNameFromUserLists($taskList[$i]['request_id'],$userLists);
			$taskList[$i]['PM']=$this->getUserNameFromUserLists($taskList[$i]['manager_id'],$userLists);
			$taskList[$i]['Resource']=$this->getUserNameFromUserLists($taskList[$i]['developer_id'],$userLists);
			$taskList[$i]['Prior']=$this->getPrior($taskList[$i]['prior_reference'],$prior_reference);
			$taskList[$i]['Property']=$this->getEntityValue('property', $taskList[$i]['property_id']);
			$taskList[$i]['Status']=$this->getEntityValue('status', $taskList[$i]['task_status']);
		}
		return $taskList;
	}

	public function getPrior($id,$prior_reference) {

		$Prior='--';

		if($id==0){
			$Prior='--';
		}
		else
		{
			if($prior_reference[$id]<>"")
			{
				$Prior=$prior_reference[$id];
			}
		}

		return $Prior;
	}

	public function getUserNameFromUserLists($id,$userLists) {

		$username="";
		for($i=0;$i<count($userLists);$i++){
			//print
			if($userLists[$i]['id']==$id){
			  $username=$userLists[$i]['name'];
			}
		}

		return $username;
	}

	public function getUserLists() {
		$taskList = array ();
		$sql = 'select id, name from tt_user where name<>""';

		$userLists = $this->_db->fetchAll($sql);
		return $userLists;
	}

	public function getUserTasksList($params = array ()){

		$util = new Utils();
		$topTaskList=$this->getTopTasks($params);

		$n=count($topTaskList);

		$topTaskIdList=""; // Add By James

		for($i=0;$i<$n;$i++){
			$topTaskIdList.=$topTaskList[$i]['id'].',';
		}

		$topTaskIdList=substr($topTaskIdList,0,-1);

		$sql = 'select tt_st_task.sup_task_id , tt_st_task.id , tt_user.name , tt_st_task.title , tt_st_task.date_start , tt_st_task.date_end  ,tt_st_task.progress , tt_st_task.request_id, tt_st_task.manager_id, tt_st_task.prior_reference  from tt_st_task,tt_user where tt_st_task.developer_id in (select id from tt_user where tt_team_id=1) ';
		$sqltail = "";
		if (count($params) > 0) {
			$sqltail .= "and tt_st_task.date_end>='".$params['startDate']."'";
			$sqltail .= "and tt_st_task.date_start<='".$params['endDate']."'";
		}

		if(trim($topTaskIdList) ==""){
			$topTaskIdList = "0";
		}

		$sql .= $sqltail . " and tt_user.id=tt_st_task.developer_id and sup_task_id not in(".$topTaskIdList.") and top_task_id in (".$topTaskIdList.") order by tt_st_task.developer_id";
		$taskList = $this->_db->fetchAll($sql);

		$userLists=$this->getUserLists();

		$prior_reference=$this->getEntities();
		$prior_reference=$prior_reference['prior_reference'];

		for($i=0;$i<count($taskList);$i++){
			$taskList[$i]['Requester']=$this->getUserNameFromUserLists($taskList[$i]['request_id'],$userLists);
			$taskList[$i]['PM']=$this->getUserNameFromUserLists($taskList[$i]['manager_id'],$userLists);
			//$taskList[$i]['Resource']=$this->getUserNameFromUserLists($taskList[$i]['developer_id'],$userLists);
			$taskList[$i]['Prior']=$this->getPrior($taskList[$i]['prior_reference'],$prior_reference);
		}
		return $taskList;
	}


	public function getUserTasksCart($params = array ()){

		$util = new Utils();
		$topTaskList=$this->getTopTasks($params);

		$n=count($topTaskList);

		for($i=0;$i<$n;$i++){
			$topTaskIdList.=$topTaskList[$i]['id'].',';
		}

		$topTaskIdList=substr($topTaskIdList,0,-1);

		$sql = 'select tt_st_task.top_task_id , tt_st_task.sup_task_id , tt_st_task.id , tt_user.name , tt_st_task.title , tt_st_task.date_start , tt_st_task.date_end , tt_st_task.progress from tt_st_task,tt_user where tt_st_task.developer_id in (select id from tt_user where tt_team_id=1) ';
		$sqltail = "";
		if (count($params) > 0) {
			$sqltail .= "and tt_st_task.date_end>='".$params['startDate']."'";
			$sqltail .= "and tt_st_task.date_start<='".$params['endDate']."'";
		}

		if(trim($topTaskIdList) ==""){
			$topTaskIdList = "0";
		}

		$sql .= $sqltail . " and tt_user.id=tt_st_task.developer_id and sup_task_id not in(".$topTaskIdList.") and top_task_id in (".$topTaskIdList.") order by tt_st_task.developer_id";

		$taskList = $this->_db->fetchAll($sql);

		$wdaystart = 0;
		$wdayend = 0;

		for($i=0;$i<count($taskList);$i++){
			if($taskList[$i]['date_start']<=$params['startDate']){
				$wdaystart=1;
			}
			else{
				$wdaystart=$util->SubDay($taskList[$i]['date_start'],$params['startDate'])+1;
			}

			if($taskList[$i]['date_end']>=$params['endDate']){
				$wdayend=6;
			}
			else{
				$wdayend=6-$util->SubDay($params['endDate'],$taskList[$i]['date_end']);
			}

			$taskList[$i]['wdaystart']=$wdaystart;
			$taskList[$i]['wdayend']=$wdayend;
		}

		return $taskList;

	}

	public function getTopTasks($params = array ()){

		$topTaskList = array ();

		$util = new Utils();

		$sql = 'select tt_st_task.sup_task_id , tt_st_task.id , tt_st_task.title , tt_user.name from tt_st_task,tt_user where tt_st_task.developer_id in (select id from tt_user where tt_team_id=1) ';
		$sqltail = "";
		if (count($params) > 0) {

			$sqltail .= "and tt_st_task.date_end>='".$params['startDate']."'";
			$sqltail .= "and tt_st_task.date_start<='".$params['endDate']."'";

		}

		$sql .= $sqltail . " and tt_user.id=tt_st_task.developer_id and tt_st_task.sup_task_id=0 order by tt_st_task.developer_id";
		$topTaskList = $this->_db->fetchAll($sql);
		return $topTaskList;

	}
	
	public function markSequence() {
		$sql = "select min(sequence) from tt_st_task";
		return $this->_db->fetchOne($sql) - 1;
	}
}
?>